from odoo import fields, models, api
from odoo.exceptions import UserError
from ...api.encapsulate.shipment import Shipment
from ...api.encapsulate.orders import Orders
from datetime import datetime

shippypro_state_code = {
    "1": "info_received",
    "2": "in_transit",
    "3": "out_for_delivery",
    "4": "missed_delivery",
    "5": "exception",
    "6": "delivered",
}
state_tran = {
    "info_received": "created",
    "in_transit": "in_transit",
    "out_for_delivery": "delivery",
    "missed_delivery": "missed_delivery",
    "exception": "exception",
    "delivered": "delivered",
}


class RPShipmentInherit(models.Model):
    _inherit = "rp.shipment"

    # shippypro数据
    shippypro_flag = fields.Boolean(string="ShipPyPro对接", default=False)
    shippypro_desc = fields.Text(string="ShipPyPro对接描述", tracking=True)

    shippypro_tracking_number = fields.Char(string="ShipPyPro追踪编号")
    shippypro_code = fields.Char(string="ShipPyPro订单号", help="NewOrderId")
    shippypro_state = fields.Selection(
        string="ShipPyPro状态",
        selection=[
            ("info_received", "收到消息"),
            ("in_transit", "正在运输"),
            ("out_for_delivery", "正在派件"),
            ("missed_delivery", "错误交货"),
            ("exception", "异常"),
            ("delivered", "已送达"),
        ],
        tracking=True,
    )
    shippypro_estimated_delivery = fields.Datetime(string="预计交货时间", tracking=True)
    rp_shipment_tracking_ids = fields.One2many(string="运输追踪", comodel_name="rp.shipment.tracking", inverse_name="rp_shipment_id")

    # @api.model
    # def create(self, vals):
    #     return super().create(vals)

    # @api.model
    # def read(self, fields=None, load='_classic_read'):
    #     return super().read(fields, load)

    ## 推送三方订单
    def action_thrid_sync(self):
        # super().action_thrid_sync()
        return self.create_shippypro_order()

    def get_tracking(self):
        """获取订单运输状态"""
        if self.shippypro_flag and self.shippypro_tracking_number:
            flag, result = Orders.get_order_tracking(self.shippypro_tracking_number)
            if flag:
                shippypro_state = shippypro_state_code.get(str(result["status_code"]))
                state = state_tran.get(shippypro_state)
                values = {
                    "shippypro_state": shippypro_state,
                    "state": state,
                    "shippypro_desc": "获取订单运输状态成功",
                }
                if result["estimated_delivery_date"] != "0":
                    values.update(
                        {
                            "shippypro_estimated_delivery": datetime.utcfromtimestamp(
                                result["estimated_delivery_date"]
                            )
                        }
                    )
                self.write(values)
            else:
                self.write(
                    {
                        "shippypro_desc": "获取订单运输状态失败，失败原因{}".format(
                            result
                        )
                    }
                )
        else:
            raise UserError("ShipPyPro没有对接成功，无法获取运输状态")

    def cancel_shipment(self):
        # 运单无法作废
        # todo 调用shippypro接口，修改订单，添加备注已作废
        super().cancel_shipment()
        return
        """作废是同时将ShipPyPro订单作废"""

        if self.third_type != "shippypro":
            return

        if self.state == "created":
            if not self.shippypro_code:
                self.write(
                    {"state": "cancel", "remarks": "已手动作废", "active": False}
                )
            else:
                Orders.delete_an_order(
                    self.code, self.shippypro_code
                )
                super().cancel_shipment()
                self.write(
                        {
                            "state": "cancel",
                            "remarks": "已手动作废,并同步删除ShipPyPro",
                            "active": False,
                        }
                    )
                # self.write(
                #     {
                #         "shippypro_desc": "删除ShipPyPro订单失败,失败原因：{}".format(
                #             result
                #         )
                #     }
                # )
        else:
            raise UserError("不在未发货状态")

    def create_shippypro_order(self):
        """创建ShipPyPro订单"""
        # 获取公司商用email
        email = self.env["ir.config_parameter"].search([("key", "=", "palment_email")])
        # 获取发件地址信息
        # sender = self.ship_from
        from_address = Shipment.address(
            self.send_first_name,
            self.send_company_name,
            self.send_country_id.code,
            self.send_state_id.name,
            self.send_city_id.name,
            self.send_street,
            self.send_postal_code_id.name,
            self.send_phone,
            self.send_email if self.send_email else ''
        )
        # 获取收件地址信息
        # receiver = self.ship_to
        to_address = Shipment.address(
            self.receive_first_name,
            self.receive_company_name,
            self.receive_country_id.code,
            self.receive_state_id.name,
            self.receive_city_id.name,
            self.receive_street,
            self.receive_postal_code_id.name,
            self.receive_phone,
            self.receive_email if self.receive_email else ''
        )
        # 获取包裹信息
        parcel_list = []
        parcel_desc = ""
        parcel_values = 0.0
        for p in self.rp_parcel_ids:
            parcel_list.append(
                {
                    "length": p.depth,
                    "width": p.width,
                    "height": p.height,
                    "weight": p.weight,
                    "parcel_id": "",
                    "parcel_type": "",
                }
            )
            parcel_desc += p.desc
            parcel_values += p.values
        parcels = Shipment.parcels(parcel_list, parcel_desc, parcel_values)
        # 获取保险信息
        insurance = Shipment.insurance(0.0)
        # 获取承运商增资
        currier_options_list = []
        # for o in self.rp_shipment_value_added_line_ids:
        #     if o.flag:
        #         currier_options_list.append({'name': o.courier_options_id.name, 'value': o.char_one})
        if not currier_options_list:
            currier_options_list = [{"name": " ", "value": " "}]
        # 获取承运商服务
        courier_service = Shipment.courier_service(
            self.shipper_id.courier_id.name,
            self.shipper_mail_route_id.name,
            int(self.shipper_mail_route_id.courier_mail_route_id.third_server_id),
            currier_options_list,
        )
        # 调用创建订单接口
        shipment = Shipment.create_ship(
            to_address, from_address, parcels, insurance, courier_service, self.code
        )
        error_message = shipment.get("ErrorMessage", False)
        if not error_message:
            self.write(
                {
                    "shippypro_flag": True,
                    "third_sync_flag": True,
                    "shippypro_desc": "连接成功",
                    "shippypro_code": shipment["NewOrderID"],
                    "label_url": (
                        shipment["LabelURL"] if shipment["LabelURL"] else False
                    ),
                    "pdf": shipment["PDF"][0] if len(shipment["PDF"]) > 0 else False,
                    "tracking_external_link": shipment["TrackingExternalLink"],
                    "shippypro_tracking_number": shipment["TrackingNumber"],
                    "shippypro_state": shippypro_state_code[shipment["Status"]],
                }
            )
            # self.create_book_pickup()
        else:
            self.write(
                {
                    "shippypro_flag": False,
                    "third_sync_flag": False,
                    "shippypro_desc": error_message,
                }
            )
            self.env.cr.commit()
            raise UserError(error_message)

        # if flag:

        # else:
        #     self.write(
        #         {
        #             "shippypro_flag": False,
        #             "third_sync_flag": True,
        #             "shippypro_desc": shipment,
        #         }
        #     )

    # def create_book_pickup(self):
    #     """ 创建shippypro订单后，自动预约上门取件 """
    #     rcd = super(RPShipmentInherit,self).create_book_pickup()
    #     rcd.confirm_book()
